// stores/user.js
import { defineStore } from 'pinia';

export const useUserStore = defineStore('user', {
  state: () => ({
    avatar: '',
    username: '',
    gender: '',
    age: '',
  }),
  actions: {
    async fetchUserInfo() {
      const resp = await fetch('http://localhost:3000/api/users/1');
      const data = await resp.json();
      this.avatar = data.avatar || 'https://via.placeholder.com/50';
      this.username = data.username || '用户名';
      this.gender = data.gender || '未知';
      this.age = data.age || '';
    },

    // ✅ 实际调用后端 PUT 更新头像
    async updateAvatar(newAvatar) {
      const resp = await fetch('http://localhost:3000/api/users/1', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ avatar: newAvatar }),
      });

      if (!resp.ok) {
        console.error('更新头像失败');
        return;
      }

      const data = await resp.json();
      this.avatar = data.avatar || newAvatar || 'https://via.placeholder.com/50';
      if (data.username) this.username = data.username;
      if (data.gender) this.gender = data.gender;
      if (data.age) this.age = data.age;
      console.log('Avatar updated to:', this.avatar);
    },
  },
});
